package com.molichuxing.gateway.utils;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.gateway.bff.orders.entity.response.DeliveryResultVo;
import com.molichuxing.gateway.contants.OrderConst;
import com.molichuxing.gateway.exception.OrderBffExceptionCodeEnum;
import com.molichuxing.gateway.property.OrderCreateTypeEnum;
import com.molichuxing.services.property.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class OrderUtil {

	/**
	 * 订单支付方式转换成用户支付方式
	 * 
	 * @param orderPayWay
	 *            支付方式
	 * @return
	 */
	public static String transUserPayWay(OrderPayWayEnum orderPayWay) {
		String userPayWay = null;
		if (OrderConst.WXPAY.contains(orderPayWay)) {
			userPayWay = "微信";
		} else if (OrderConst.ALPAY.contains(orderPayWay)) {
			userPayWay = "支付宝";
		} else if (OrderConst.UNIONPAY.contains(orderPayWay)) {
			userPayWay = "银联";
		} else if (OrderConst.OFFLINE.contains(orderPayWay)) {
			userPayWay = "线下支付";
		}
		return userPayWay;
	}

	/**
	 * 订单状态说明（app端显示）
	 * 
	 * @param orderType
	 * @param orderStatus
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String statusExplain(OrderTypeEnum orderType, Enum orderStatus) {
		String explain = null;
		if (OrderTypeEnum.EXCLUSIVEL.equals(orderType)) {
			// 专属里程订单
			explain = exclusivelStatusExplain((OrderExclusivelStatusEnum) orderStatus);
		} else if (OrderTypeEnum.SUBSCRIBE.equals(orderType)) {
			// 订阅里程订单
			explain = subscribeStatusExplain((OrderSubscribeStatusEnum) orderStatus);
		}
		return explain;
	}

	/**
	 * 专属订单状态说明（app端显示）
	 * 
	 * @param orderStatus
	 *            专属订单状态
	 * @return
	 */
	public static String exclusivelStatusExplain(OrderExclusivelStatusEnum orderStatus) {
		String explain = null;
		switch (orderStatus) {
		case TRADE_UNAUDIT:
			// 待审核
			explain = OrderConst.TRADE_UNAUDIT_EXPLAIN;
			break;
		case TRADE_REJECTED:
			// 审核驳回
			explain = OrderConst.TRADE_REJECTED_EXPLAIN;
			break;
		case TRADE_REFUND:
			// 退款中
			explain = OrderConst.TRADE_REFUND_EXPLAIN;
			break;
		case TRADE_FINISH:
			// 交易结束
			explain = OrderConst.TRADE_FINISH_EXPLAIN;
			break;
		case TRADE_UNDELIVERY:
			// 待提车
			explain = OrderConst.TRADE_UNDELIVERY_EXPLAIN;
			break;
		default:
			break;
		}
		return explain;
	}

	/**
	 * 订阅订单状态说明（app端显示）
	 * 
	 * @param orderStatus
	 *            订阅订单状态
	 * @return
	 */
	public static String subscribeStatusExplain(OrderSubscribeStatusEnum orderStatus) {
		String explain = null;
		switch (orderStatus) {
		case TRADE_UNAUDIT:
			// 待审核
			explain = OrderConst.TRADE_UNAUDIT_EXPLAIN;
			break;
		case TRADE_REJECTED:
			// 审核驳回
			explain = OrderConst.TRADE_REJECTED_EXPLAIN;
			break;
		case TRADE_REFUND:
			// 退款中
			explain = OrderConst.TRADE_REFUND_EXPLAIN;
			break;
		case TRADE_FINISH:
			// 交易结束
			explain = OrderConst.TRADE_FINISH_EXPLAIN;
			break;
		case TRADE_UNDELIVERY:
			// 待提车
			explain = OrderConst.TRADE_UNDELIVERY_EXPLAIN;
			break;
		case TRADE_UNUSE:
			// 待用车
			explain = OrderConst.TRADE_UNUSE_EXPLAIN;
			break;
		case RETURN_UNINSPECTED:
			// 待验车
			explain = OrderConst.RETURN_UNINSPECTED_EXPLAIN;
			break;
		case RETURN_UNCONFIRM:
			// 报告待确认
			explain = OrderConst.RETURN_UNCONFIRM_EXPLAIN;
			break;
		case RETURN_INTERVENE:
			// 待人工介入
			explain = OrderConst.RETURN_INTERVENE_EXPLAIN;
			break;
		case RETURN_UNPAID:
			// 待缴费
			explain = OrderConst.RETURN_UNPAID_EXPLAIN;
			break;
		default:
			break;
		}
		return explain;
	}

	/**
	 * 加购、续订验证时间
	 * 
	 * @param leaseExpire
	 * @param createType
	 * @throws Exception
	 */
	public static void verifyDate(LocalDate leaseExpire, Long orderCode, OrderCreateTypeEnum createType,
			Logger logger) throws BizException {
		Integer day = (int) DateUtil.getDaysDiff(leaseExpire, LocalDateTime.now());
		if (day > 0) {
			// 当前日期大于应还车日期
			logger.error("[verifyDate]该订单({})已超时", orderCode);
			throw new BizException(OrderBffExceptionCodeEnum.CANNOT_RELET.getCode(),
					OrderCreateTypeEnum.PURCHASED.equals(createType) ? "因您操作超时，当前订单已超时，不能办理加购。"
							: "因您操作超时，当前订单已超时，不能办理续订。");
		} else {
			// 当前日期等于应还车日期，判断时间（默认最晚18点）
			LocalDateTime lastTime = DateUtil.plus(LocalDateTime.now(), 10, ChronoUnit.MINUTES);
			if (lastTime.isAfter(DateUtil.parseDateTime(DateUtil.formatDate(leaseExpire) + " 18:00:00"))) {
				// 当前时间大于18点
				logger.error("[verifyDate]该订单({})已超时，续订业务已关闭", orderCode);
				throw new BizException(OrderBffExceptionCodeEnum.CANNOT_RELET.getCode(),
						OrderCreateTypeEnum.PURCHASED.equals(createType) ? "您已超时，加购里程业务已关闭，不能线上办理。"
								: "您已超时，续订业务已关闭，不能线上办理。");
			}
		}
	}

	public static String getOrderChannel(OrderSourceEnum orderSource) {
		String orderChannel = null;
		switch (orderSource) {
		case AIO:
			orderChannel = "智能交易终端";
			break;
		case ANDROID:
			orderChannel = "茉莉出行APP";
			break;
		case IOS:
			orderChannel = "茉莉出行APP";
			break;
		case JSAPI:
			orderChannel = "微信公众号";
			break;
		case APPLET:
			orderChannel = "微信小程序";
			break;
		case MWEB:
			orderChannel = "M端";
			break;
		default:
			break;
		}
		return orderChannel;
	}

	public static String getOrderExplain(OrderExclusivelStatusEnum orderStatus, Boolean isPlaceStore) {
		String explain = null;
		if (OrderExclusivelStatusEnum.TRADE_UNPAID.equals(orderStatus)) {
			// 待付款
			// explain = isPlaceStore ? null : "请到下单门店进行支付";
		} else if (OrderExclusivelStatusEnum.TRADE_UNDELIVERY.equals(orderStatus)) {
			// 待提车
			explain = isPlaceStore ? null : "请到提车门店办理提车";
		} else if (OrderExclusivelStatusEnum.TRADE_USE.equals(orderStatus)) {
			// 用车中
			explain = isPlaceStore ? null : "请到下单门店办理相关业务";
		} else {
			// 其他状态
			explain = isPlaceStore ? "您的订单尚未完成,请前往APP及时处理" : "请到下单门店办理相关业务";
		}
		return explain;
	}

	public static String getOrderExplain(OrderSubscribeStatusEnum orderStatus, Boolean isPlaceStore) {
		String explain = null;
		if (OrderSubscribeStatusEnum.TRADE_UNPAID.equals(orderStatus)) {
			// 待付款
			// explain = isPlaceStore ? null : "请到下单门店进行支付";
		} else if (OrderSubscribeStatusEnum.TRADE_UNDELIVERY.equals(orderStatus)) {
			// 待提车
			explain = isPlaceStore ? null : "请到提车门店办理提车";
		} else if (OrderSubscribeStatusEnum.TRADE_USE.equals(orderStatus)) {
			// 用车中
			explain = isPlaceStore ? null : "请到下单门店办理相关业务";
		} else {
			// 其他状态
			explain = isPlaceStore ? "您的订单尚未完成,请前往APP及时处理" : "请到下单门店办理相关业务";
		}
		return explain;
	}

	/**
	 * 门店已关店
	 * 
	 * @param resultVo
	 */
	public static void storeClose(DeliveryResultVo resultVo) {
		resultVo.setResult(false);
		resultVo.setExplain("门店已关店！");
	}

	/**
	 * 门店已暂停营业
	 * 
	 * @param resultVo
	 */
	public static void storeSuspension(DeliveryResultVo resultVo) {
		resultVo.setResult(false);
		resultVo.setExplain("门店已暂停营业！");
	}

	/**
	 * 重新选车
	 * 
	 * @param resultVo
	 */
	public static void carFailed(DeliveryResultVo resultVo) {
		resultVo.setResult(false);
		resultVo.setExplain("重新选车！");
		resultVo.setAgain(true);
	}

	/**
	 * 身份证脱敏
	 * 
	 * @param idCard
	 * @return
	 */
	public static String desensitizeIdCard(String idCard) {
		if (idCard == null) {
			return "";
		}
		return replaceBetween(idCard, 6, idCard.length() - 4, null);
	}

	/**
	 * 手机号脱敏
	 * 
	 * @param phone
	 *            手机号
	 * @return
	 */
	public static String desensitizePhone(String phone) {
		if (phone == null) {
			return "";
		}
		return replaceBetween(phone, 3, phone.length() - 4, null);
	}

	private static String replaceBetween(String sourceStr, int begin, int end, String replacement) {
		if (sourceStr == null) {
			return "";
		}
		if (replacement == null) {
			replacement = "*";
		}
		int replaceLength = end - begin;
		if (StringUtils.isNotBlank(sourceStr) && replaceLength > 0) {
			StringBuilder sb = new StringBuilder(sourceStr);
			sb.replace(begin, end, StringUtils.repeat(replacement, replaceLength));
			return sb.toString();
		} else {
			return sourceStr;
		}
	}

	public static String transformStatus(OrderExclusivelStatusEnum orderStatus, OrderRenegeCostTypeEnum costType) {
		String result = orderStatus.getName();
//		if (OrderStatusConst.RENEGE_EXCLUSIVEL_STATUS.contains(orderStatus)) {
		if (OrderExclusivelStatusEnum.RENEGE_ACCEPTED.equals(orderStatus)) {
			result = "退租待还车";
		} else if (OrderExclusivelStatusEnum.RENEGE_REFUND.equals(orderStatus)) {
			if (OrderRenegeCostTypeEnum.INCOME.equals(costType)) {
				result = "退租待缴费";
			}
		} else if (OrderExclusivelStatusEnum.RENEGE_UNPAID.equals(orderStatus)) {
			result = "退租退款中";
		}

		return result;
	}

}
